package com.longrise.co.ui.home.fragment;

import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.longrise.co.R;
import com.longrise.co.api.ApiConstants;
import com.longrise.co.ui.home.adapter.CarCompanyAdapter;
import com.longrise.co.ui.home.contract.HomeContract;
import com.longrise.co.ui.home.model.CarCompany;
import com.longrise.co.ui.home.model.DictionaryBean;
import com.longrise.co.ui.home.model.HomeModel;
import com.longrise.co.ui.home.presenter.HomePresenter;
import com.longrise.co.ui.home.widget.CompanyQueryPopWindow;
import com.longrise.co.utils.Constants;
import com.ly.common.base.BaseFragment;
import com.ly.common.commonutils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by luoyang on 2017-7-13.
 */

public class CompanyQueryFragment extends BaseFragment<HomePresenter, HomeModel> implements HomeContract.View<CarCompany>, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnRecyclerViewItemClickListener {

    @Bind(R.id.head_title)
    TextView headTitle;

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.search_content)
    EditText searchContent;
    @Bind(R.id.qualification_tv)
    TextView qualificationTv;

    @Bind(R.id.satisfaction_tv)
    TextView satisfactionTv;
    @Bind(R.id.select)
    LinearLayout mSelect;
    @Bind(R.id.search_no_data_tv)
    TextView searchNoDataTv;
    @Bind(R.id.no_data_tip)
    RelativeLayout noDataTip;

    private CarCompanyAdapter mAdapter;

    private CompanyQueryPopWindow mPopWindow;
    //资质列表
    private List<DictionaryBean> mQualificationList;
    //满意度列表
    private List<DictionaryBean> mSatisfactionList;

    private int mPageCount = 0;

    private int mPageNum = 1;

    //资质查询条件
    private String mQualificationStr;
    //排序查询条件
    private String mSatisfactionStr;

    @Override
    protected int getLayoutResource() {
        return R.layout.fg_company_query;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    protected void initView() {
        headTitle.setText("企业查询");
        noDataTip.setVisibility(View.GONE);
        searchNoDataTv.setText("未查询到相关企业记录");
        initRecyclerView();
        initPopWindow();
        mPresenter.getCarCompany(mPageNum,ApiConstants.PAGE_SIZE_10,null, null, null , true);

        mRxManager.on(Constants.RX_EVENT_COMPANY_SEARCH, new Action1<DictionaryBean>() {
            @Override
            public void call(DictionaryBean dictionaryBean) {
                if(dictionaryBean == null) {
                    return ;
                }

                boolean isTitle = "不限".equals(dictionaryBean.getValue());
                if(dictionaryBean.getType() == 1) {
                    //如果不限
                    mQualificationStr = dictionaryBean.getCode();
                    qualificationTv.setText(isTitle ? "资质" : dictionaryBean.getValue());
                } else if(dictionaryBean.getType() == 2) {
                    mSatisfactionStr = dictionaryBean.getCode();
                    satisfactionTv.setText(isTitle? "排序" : dictionaryBean.getValue());
                }
                mPopWindow.dismiss();
                searchData(true);
            }
        });
    }

    private void initPopWindow() {
        if (mPopWindow == null) {
            mPopWindow = new CompanyQueryPopWindow(_mActivity);
        }

        if (mQualificationList == null) {
            mQualificationList = new ArrayList<>();
            mQualificationList.add(new DictionaryBean("", "不限", 1));
            mQualificationList.add(new DictionaryBean("01", "一类维修经营业务", 1));
            mQualificationList.add(new DictionaryBean("02", "二类维修经营业务", 1));
            mQualificationList.add(new DictionaryBean("03", "三类维修经营业务", 1));
        }

        if (mSatisfactionList == null) {
            mSatisfactionList = new ArrayList<>();
            mSatisfactionList.add(new DictionaryBean("", "不限", 2));
            mSatisfactionList.add(new DictionaryBean("1", "按企业好评数排序", 2));
            mSatisfactionList.add(new DictionaryBean("2", "按评价满意度排序", 2));
        }
    }


    private void initRecyclerView() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(Constants.RECYCLER_RGB);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(layoutManager);
        mAdapter = new CarCompanyAdapter(getContext(), null);

        mAdapter.setOnLoadMoreListener(this);
        mAdapter.openLoadMore(ApiConstants.PAGE_SIZE_10, true);
        mAdapter.setOnRecyclerViewItemClickListener(this);
        recyclerView.setAdapter(mAdapter);
    }

    public static CompanyQueryFragment newInstance() {
        return new CompanyQueryFragment();
    }

    @Override
    public void requestSuccess(CarCompany info) {
        if (info != null && info.getList() != null && info.getList().size() > 0) {

            mPageCount = Integer.parseInt(info.getTotalnum());
            if (mPageNum == 1) {
                //刷新
                mAdapter.setNewData(info.getList());
            } else {
                //加载更多
                mAdapter.notifyDataChangedAfterLoadMore(info.getList(), true);
            }
        } else {
            //没有搜索到结果
            noDataTip.setVisibility(mPageNum == 1 ? View.VISIBLE : View.GONE);
            mPageNum--;
            mPageCount = mPageNum;
            mAdapter.notifyDataChangedAfterLoadMore(false);
            if (mPageNum > 1) {
                showLongToast("全部加载完毕");
            }
        }
    }

    @Override
    public void onRequestComplete(int type) {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(false);
        }
    }


    @OnClick({R.id.head_back, R.id.start_search, R.id.qualification_rl, R.id.satisfaction_rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_back:
                _mActivity.onBackPressed();
                break;
            case R.id.start_search:
                if(StringUtils.isEmpty(searchContent.getText().toString())) {
                    showErrorTip("请输入企业名称进行搜索");
                    return;
                }
                searchData(true);
                break;
            case R.id.qualification_rl:
                mPopWindow.setNewData(mQualificationList);
                mPopWindow.showPopupWindow(mSelect);
                break;
            case R.id.satisfaction_rl:
                mPopWindow.setNewData(mSatisfactionList);
                mPopWindow.showPopupWindow(mSelect);
                break;
        }
    }

    private void searchData(boolean isProcess) {
        mPageNum = 1;
        noDataTip.setVisibility(View.GONE);
        mAdapter.notifyDataChangedAfterLoadMore(true);
        mPresenter.getCarCompany(mPageNum,ApiConstants.PAGE_SIZE_10, searchContent.getText().toString(), mQualificationStr, mSatisfactionStr , isProcess);
    }

    @Override
    public void onRefresh() {
        searchData(false);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (mPageNum < mPageCount) {
                    //还有更多数据
                    mPresenter.getCarCompany(++mPageNum,ApiConstants.PAGE_SIZE_10,searchContent.getText().toString() ,mQualificationStr, mSatisfactionStr , false);
                } else {
                    mAdapter.notifyDataChangedAfterLoadMore(false);
                }
            }

        }, 2000);

    }

    @Override
    public void onItemClick(View view, int i) {
        CarCompany.ListBean bean = mAdapter.getItem(i);
        if(bean != null) {
            start(CompanyDetailFragment.newInstance(bean.getCompanyid(), bean.getAreaid()));
        }
    }
}
